<?php

namespace plugin\ycMassage\app\shop\controller;

use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAlarm;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageShopStatistics;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianScheduling;
use plugin\ycMassage\utils\enum\AlarmState;
use plugin\ycMassage\utils\enum\ServiceState;
use support\Request;
use think\facade\Cache;

/**
 * 默认首页
 *
 * @author 贵州猿创科技有限公司
 * @Email 416716328@qq.com
 * @DateTime 2023-03-07
 */
class IndexController extends BaseController
{
    /**
     * 无需验证APPID方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedAppid = ['index'];

    /**
     * 无需登录方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedLogin = ['index'];

    /**
     * 无需鉴权方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedAuth = ['index'];

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }

    /**
     * 渲染后台
     * @param \support\Request $request
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function index(Request $request)
    {
        return getAdminView($request->plugin);
    }
    public function statistic(Request $request)
    {
        $shops = [];
        $where = [];
        $technicianWhere = [];
        $where[] = ['saas_appid', '=', $request->saas_appid];
        $technicianWhere[] = ['saas_appid', '=', $request->saas_appid];
        $shop_id = $request->get('shop_id');
        $day = (int)$request->get('day', 7);
        if (!$day) {
            $day = 7;
        }
        $cacheKey = "Massage.statistic.echarts.{$day}";
        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
            $technicianWhere[] = ['work_shop_id', '=', $shop_id];
            $cacheKey .= ".shop.{$shop_id}";
        } else {
            if ($request->use_mch_id) {
                $where[] = ['mch_id', '=', $request->use_mch_id];
                $technicianWhere[] = ['work_mch_id', '=', $request->use_mch_id];
                $cacheKey .= ".mch.{$request->use_mch_id}";
            } else {
                $where[] = ['shop_id', '=', $request->use_shop_id];
                $technicianWhere[] = ['work_shop_id', '=', $request->use_shop_id];
                $cacheKey .= ".shop.{$request->use_shop_id}";
            }
        }
        if ($request->use_mch_id) {
            $shops = MassageShop::where('mch_id', $request->use_mch_id)->field('id as value,title as label')->select();
        }
        $echarts = Cache::get($cacheKey);
        $technicianIds = MassageUserTechnician::where($technicianWhere)->column('uid');
        $Scheduling = MassageUserTechnicianScheduling::where($where)->whereIn('uid', $technicianIds)
            ->whereBetweenTimeField('start_time', 'end_time')->count('uid');
        $sum = count($technicianIds);
        $working = MassageAppointmentService::where($where)->whereIn('state', [
            ServiceState::TRAVELING['value'],
            ServiceState::ARRIVAL['value'],
            ServiceState::ING['value']
        ])->count('technician_id');
        $technician = [
            'sum' => $sum,
            'resting' => $sum - $Scheduling,
            'idle' => $Scheduling - $working,
            'working' => $working,
            'alarm'=>MassageAlarm::where($where)->where('state',AlarmState::WAIT['value'])->count()
        ];
        if (!$echarts) {
            $series = [
                'name' => '',
                'type' => 'line',
                'stack' => 'Total',
                'smooth' => true,
                'data' => [],
            ];
            $echarts = [
                'legend' => [
                    'data' => ['人次', '服务时长', '订单量', '营业额']
                ],
                'xAxis' => [
                    'data' => []
                ],
                'series' => []
            ];
            $person_time = [];
            $duration = [];
            $orders_num = [];
            $orders_price = [];
            for ($i = $day; $i > 0; $i--) {
                $time = strtotime("-{$i} day");
                $whereDay = date('Y-m-d', $time);
                $date = date('m-d', $time);
                $echarts['xAxis']['data'][] = $date;
                $person_time[] = MassageShopStatistics::where($where)->whereDay('create_time', $whereDay)->sum('person_time');
                $duration[] = MassageShopStatistics::where($where)->whereDay('create_time', $whereDay)->sum('duration');
                $orders_num[] = MassageShopStatistics::where($where)->whereDay('create_time', $whereDay)->sum('orders_num');
                $orders_price[] = MassageShopStatistics::where($where)->whereDay('create_time', $whereDay)->sum('orders_price');
            }
            $series['name'] = '人次';
            $series['data'] = $person_time;
            $echarts['series'][] = $series;
            $series['name'] = '服务时长';
            $series['data'] = $duration;
            $echarts['series'][] = $series;
            $series['name'] = '订单量';
            $series['data'] = $orders_num;
            $echarts['series'][] = $series;
            $series['name'] = '营业额';
            $series['data'] = $orders_price;
            $echarts['series'][] = $series;
            $ttl = strtotime('23:59:59') - time();
            Cache::set($cacheKey, $echarts, $ttl);
        }
        $today = [
            'person_time' => MassageShopStatistics::where($where)->whereDay('create_time')->sum('person_time'),
            'duration' => MassageShopStatistics::where($where)->whereDay('create_time')->sum('duration'),
            'orders_num' => MassageShopStatistics::where($where)->whereDay('create_time')->sum('orders_num'),
            'orders_price' => MassageShopStatistics::where($where)->whereDay('create_time')->sum('orders_price')
        ];
        $yesterday = [
            'person_time' => MassageShopStatistics::where($where)->whereDay('create_time', 'yesterday')->sum('person_time'),
            'duration' => MassageShopStatistics::where($where)->whereDay('create_time', 'yesterday')->sum('duration'),
            'orders_num' =>  MassageShopStatistics::where($where)->whereDay('create_time', 'yesterday')->sum('orders_num'),
            'orders_price' => MassageShopStatistics::where($where)->whereDay('create_time', 'yesterday')->sum('orders_price')
        ];
        $growth_rate = [
            'person_time' =>  $today['person_time'] > 0 ? round(($today['person_time'] - $yesterday['person_time']) / $yesterday['person_time'] * 100, 2) : 0,
            'duration' => $today['duration'] > 0 ? round(($today['duration'] - $yesterday['duration']) / $yesterday['duration'] * 100, 2) : 0,
            'orders_num' => $today['orders_num'] > 0 ? round(($today['orders_num'] - $yesterday['orders_num']) / $yesterday['orders_num'] * 100, 2) : 0,
            'orders_price' => $today['orders_price'] > 0 ? round(($today['orders_price'] - $yesterday['orders_price']) / $yesterday['orders_price'] * 100, 2) : 0
        ];
        $statistic = [
            'technician' => $technician,
            'today' => $today,
            'yesterday' => $yesterday,
            'growth_rate' => $growth_rate
        ];
        $data = [
            'echarts'          =>  $echarts,
            'statistic'         => $statistic,
            'shops' => $shops
        ];
        return $this->successRes($data);
    }
}
